#!/bin/bash

# XY User System 部署脚本
# 使用方法: ./deploy.sh [环境] [操作]
# 环境: production (默认)
# 操作: deploy, update, stop, restart, logs

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置
APP_NAME="xyuser-system"
DOCKER_COMPOSE_FILE="docker-compose.yml"
BACKUP_DIR="./backups"

# 函数定义
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查Docker和Docker Compose
check_dependencies() {
    log_info "检查依赖..."
    
    if ! command -v docker &> /dev/null; then
        log_error "Docker 未安装，请先安装 Docker"
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        log_error "Docker Compose 未安装，请先安装 Docker Compose"
        exit 1
    fi
    
    log_success "依赖检查完成"
}

# 创建必要的目录
create_directories() {
    log_info "创建必要的目录..."
    mkdir -p $BACKUP_DIR
    mkdir -p ./public/uploads
    mkdir -p ./ssl
    mkdir -p ./mysql-init
    log_success "目录创建完成"
}

# 备份数据库
backup_database() {
    log_info "备份数据库..."
    
    if docker-compose ps mysql | grep -q "Up"; then
        BACKUP_FILE="$BACKUP_DIR/mysql_backup_$(date +%Y%m%d_%H%M%S).sql"
        docker-compose exec -T mysql mysqldump -u xyuser -pyour_secure_password_here xyuser_db > "$BACKUP_FILE"
        log_success "数据库备份完成: $BACKUP_FILE"
    else
        log_warning "MySQL 容器未运行，跳过备份"
    fi
}

# 部署应用
deploy() {
    log_info "开始部署 $APP_NAME..."
    
    check_dependencies
    create_directories
    
    # 检查配置文件
    if [ ! -f ".env.production" ]; then
        log_warning ".env.production 文件不存在，请先配置环境变量"
    fi
    
    # 构建并启动服务
    log_info "构建并启动服务..."
    docker-compose -f $DOCKER_COMPOSE_FILE build --no-cache
    docker-compose -f $DOCKER_COMPOSE_FILE up -d
    
    # 等待服务启动
    log_info "等待服务启动..."
    sleep 30
    
    # 检查服务状态
    check_health
    
    log_success "部署完成！"
    show_status
}

# 更新应用
update() {
    log_info "更新 $APP_NAME..."
    
    backup_database
    
    # 拉取最新代码（如果使用Git）
    if [ -d ".git" ]; then
        log_info "拉取最新代码..."
        git pull origin master
    fi
    
    # 重新构建并重启
    log_info "重新构建应用..."
    docker-compose -f $DOCKER_COMPOSE_FILE build --no-cache app
    docker-compose -f $DOCKER_COMPOSE_FILE up -d app
    
    # 等待服务启动
    sleep 20
    check_health
    
    log_success "更新完成！"
}

# 停止服务
stop() {
    log_info "停止 $APP_NAME..."
    backup_database
    docker-compose -f $DOCKER_COMPOSE_FILE down
    log_success "服务已停止"
}

# 重启服务
restart() {
    log_info "重启 $APP_NAME..."
    docker-compose -f $DOCKER_COMPOSE_FILE restart
    sleep 20
    check_health
    log_success "服务已重启"
}

# 查看日志
show_logs() {
    log_info "显示应用日志..."
    docker-compose -f $DOCKER_COMPOSE_FILE logs -f --tail=100 app
}

# 检查服务健康状态
check_health() {
    log_info "检查服务健康状态..."
    
    # 检查容器状态
    if docker-compose ps | grep -q "Up"; then
        log_success "容器运行正常"
    else
        log_error "部分容器未正常运行"
        docker-compose ps
        return 1
    fi
    
    # 检查应用健康
    for i in {1..10}; do
        if curl -f http://localhost:3000/health &> /dev/null; then
            log_success "应用健康检查通过"
            return 0
        fi
        log_info "等待应用启动... ($i/10)"
        sleep 5
    done
    
    log_error "应用健康检查失败"
    return 1
}

# 显示服务状态
show_status() {
    log_info "服务状态:"
    docker-compose -f $DOCKER_COMPOSE_FILE ps
    
    echo ""
    log_info "访问地址:"
    echo "  - HTTP:  http://localhost"
    echo "  - HTTPS: https://localhost (需要配置SSL证书)"
    echo "  - 应用:  http://localhost:3000"
    echo "  - 数据库: localhost:3306"
}

# 清理资源
cleanup() {
    log_info "清理未使用的Docker资源..."
    docker system prune -f
    docker volume prune -f
    log_success "清理完成"
}

# 主函数
main() {
    local action=${1:-deploy}
    
    case $action in
        "deploy")
            deploy
            ;;
        "update")
            update
            ;;
        "stop")
            stop
            ;;
        "restart")
            restart
            ;;
        "logs")
            show_logs
            ;;
        "status")
            show_status
            ;;
        "health")
            check_health
            ;;
        "cleanup")
            cleanup
            ;;
        "backup")
            backup_database
            ;;
        *)
            echo "使用方法: $0 [deploy|update|stop|restart|logs|status|health|cleanup|backup]"
            echo ""
            echo "命令说明:"
            echo "  deploy  - 首次部署应用"
            echo "  update  - 更新应用"
            echo "  stop    - 停止所有服务"
            echo "  restart - 重启所有服务"
            echo "  logs    - 查看应用日志"
            echo "  status  - 查看服务状态"
            echo "  health  - 检查服务健康状态"
            echo "  cleanup - 清理Docker资源"
            echo "  backup  - 备份数据库"
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"